/**
 * 获取商品评分（仅需传入解析后的文档对象）
 * @param {Document} doc - 解析后的HTML文档对象
 * @returns {number|null} - 商品评分（null表示未获取到）
 */
function getAsinFromDoc(doc: Document) {
  // 1. 优先从加入购物车按钮区域的ASIN输入框获取
  const addToCartEl = doc.querySelector("#addToCart");
  let asin = addToCartEl
    ? addToCartEl.querySelector('input[name="ASIN"]')?.getAttribute("value") ||
      ""
    : "";

  // 2. 若未获取到，从文档中提取当前页面URL（优先用canonical链接）
  if (!asin) {
    const canonicalLink = doc.querySelector('link[rel="canonical"]');
    const pageUrl = canonicalLink?.getAttribute("href") || "";
    if (pageUrl) {
      const urlMatch = pageUrl.match(/\/dp\/([A-Z0-9]{10})(?:\/|$|\?)/);
      asin = urlMatch ? urlMatch[1] : "";
    }
  }
  return asin;
}

export function extractNumberRatingValue(
  doc: Document,
  marketplace: string
): number {
  // 第一步：从文档中获取ASIN（内部逻辑复用之前的ASIN提取逻辑）

  const asin = getAsinFromDoc(doc);
  let rating = 0;

  // 第二步：从#pqv-ratings元素提取评分
  const ratingsElement = doc.querySelector("#pqv-ratings");
  const ratingsText = ratingsElement?.textContent?.trim() ?? "";
  const ratingsMatch = ratingsText.match(/([\d.]+)\s+out of\s+\d+\s+stars?/i);
  if (ratingsMatch) {
    rating = parseFloat(ratingsMatch[1]);
  }

  // 第三步：若存在ASIN，从#averageCustomerReviews元素补充/覆盖评分
  if (asin) {
    const reviewElement = doc.querySelector(
      `#averageCustomerReviews[data-asin="${asin}"]`
    );
    if (reviewElement) {
      const popoverTitle = reviewElement
        .querySelector("#acrPopover")
        ?.getAttribute("title")
        ?.trim();
      const iconAltText = reviewElement
        .querySelector(".a-icon-alt")
        ?.textContent?.trim();
      const reviewText = (popoverTitle || iconAltText || "").trim();
      if (marketplace === "JPN") {
        const ratingMatch = reviewText.match(/のうち\s*([\d.]+)/);
        if (ratingMatch) {
          const parsedRating = parseFloat(ratingMatch[1]);
          if (Number.isFinite(parsedRating)) {
            rating = parsedRating;
          }
        }
      } else if(marketplace === "DEU"){
        const reviewMatch = reviewText.replace(/ /g, "").replace(/,/g, ".").match(/^\s*([\d.]+)/);
        if (reviewMatch) {
          const parsedRating = parseFloat(reviewMatch[1]);
          if (Number.isFinite(parsedRating)) {
            rating = parsedRating;
          }
        }
      } else if(marketplace === "FRA"){
        const reviewMatch = reviewText.replace(/ /g, "").replace(/,/g, ".").match(/^\s*([\d.]+)/);
        if (reviewMatch) {
          const parsedRating = parseFloat(reviewMatch[1]);
          if (Number.isFinite(parsedRating)) {
            rating = parsedRating;
          }
        }
      } else {
        const reviewMatch = reviewText.match(/^\s*([\d.]+)/);
        if (reviewMatch) {
          const parsedRating = parseFloat(reviewMatch[1]);
          if (Number.isFinite(parsedRating)) {
            rating = parsedRating;
          }
        }
      }
    }
  }

  return rating;
}
